package Offer26;

/**
 * @author 23737
 * @time 2021.9.9
 * 树的子结构：输入两棵二叉树A和B，判断B是不是A的子结构。(约定空树不是任意一个树的子结构)
 * B是A的子结构， 即 A中有出现和B相同的结构和节点值。
 */
public class Test {
    public static void main(String[] args) {
        System.out.println("hello world");
    }
}

class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) {
        val = x;
    }
}

/*我写不来，官方题解：递归*/
class Solution {
    public boolean isSubStructure(TreeNode A, TreeNode B) {
        if (B == null || A == null) {
            return false;
        }
        if (A.val == B.val && (helper(A.left, B.left) && helper(A.right, B.right))) {
            return true;
        }
        return isSubStructure(A.left, B) || isSubStructure(A.right, B);
    }

    private boolean helper(TreeNode root1, TreeNode root2) {
        if (root2 == null) {
            return true;
        }
        if (root1 == null) {
            return false;
        }
        if (root1.val == root2.val) {
            return helper(root1.left, root2.left) && helper(root1.right, root2.right);
        } else {
            return false;
        }
    }
}

class SolutionTwice{
    public boolean isSubStructure(TreeNode A, TreeNode B) {
        if (B== null || A == null) {
            return false;
        }
        if(A.val == B.val && (helper(A.left,B.left) && helper(A.right,B.right))){
            return true;
        }
        return isSubStructure(A.left,B) || isSubStructure(A.right,B);
    }

    private boolean helper(TreeNode a, TreeNode b) {
        // 对b结点的判断要放在前面，这里这次做的时候踩的坑
        /**
         * [1,2,3,4]
         * [3]
         * 像这个例子。如果把对a的判断放在了前面，那么就会返回false，但其实结果应该要为true
         */
        if (b == null) {
            return true;
        }
        if (a == null) {
            return false;
        }
        if(a.val == b.val){
            return helper(a.left,b.left) && helper(a.right,b.right);
        }else {
            return false;
        }
    }
}

